<template>
  <el-dialog
    v-dialogDrag
    :visible="isDialogVisible"
    :title="titleName"
    width="50%"
    center
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="closeEdit"
  >
    <dialogHeader
      slot="title"
      :title="titleName"
      :style-type="$store.state.app.dialogType"
    />
    <div class="filter-container filter-params">
      <one-table-template
        ref="multipleTable"
        :dynamic-api-config="apiConfig"
        :dynamic-buttons="dynamicButtons"
        :dynamic-components="tableComponents"
        :dynamic-table-cols="dynamicTableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :dynamic-export-converts="dynamicExportConverts"
        :refresh-table-key="refreshTableKey"
      />
    </div>
  </el-dialog>
</template>

<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/apiVeData'
export default {
  components: {
    dialogHeader,
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    isDialogVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    },
    titleName: {
      type: String,
      default: ''
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      refreshTableKey: '0',
      // table表格查询API配置对象
      apiConfig: {},
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '门店：',
              codeField: 'dlrFullName',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey2',
              labelName: '22位码：',
              codeField: 'ttCode',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey3',
              labelName: '制定月份：',
              codeField: 'makingMonth',
              disabled: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum()
            },
            {
              compKey: 'compKey4',
              labelName: '基数：',
              codeField: 'baseNum',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum(),
              validrule: {
                minlength: 0,
                maxlength: 10,
                // noRequire: true,
                isformat: /^[1-9]\d*$/,
                resectMessage: {
                  minlength: '请输入有效数字!',
                  maxlength: '请输入有效数字!'
                }
              }
            },
            {
              compKey: 'compKey5',
              labelName: '浮动上限(%)：',
              codeField: 'floatingCeiling',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum(),
              validrule: {
                min: 0,
                max: 100,
                isformat: /^[1-9]\d*$/,
                resectMessage: {
                  minlength: '请输入有效数字!',
                  maxlength: '请输入有效数字!'
                }
              }
            },
            {
              compKey: 'compKey6',
              labelName: '浮动下限(%)：',
              codeField: 'floatingFloor',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: this.spanNum(),
              validrule: {
                min: 0,
                max: 100,
                // noRequire: true,
                isformat: /^[1-9]\d*$/,
                resectMessage: {
                  minlength: '请输入有效数字!',
                  maxlength: '请输入有效数字!'
                }
              }
            },
            {
              compKey: 'compKey7',
              labelName: '计划月份：',
              codeField: 'planM',
              code: 'formField.planMonth',
              component: () => import('@/components/org/checkBox/month'),
              type: 'checkbox',
              isMust: true,
              span: this.spanNum()
            }
          ],
      // form 的表单对象
      formField: {
        dlrFullName: '',
        ttCode: '',
        makingMonth: '',
        baseNum: '',
        floatingCeiling: '',
        floatingFloor: '',
        planM: ''
      },

      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: 'primary',
              size: 'small',
              name: 'search',
              clickEvent: () => this.save(),
              text: '保存'
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              clickEvent: () => this.closeEdit(1),
              text: '取消'
            },
            {
              compKey: 'btnKey3',
              type: '',
              size: 'small',
              icon: 'iconfont  icon-cancel',
              name: 'reset',
              clickEvent: () => this.reset(),
              text: '清除',
              position: 'right'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      dynamicExportConverts: {
        isEnable: {
          convert: 'kvs',
          kvs: {
            '1': '是',
            '0': '否'
          }
        }
      },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.handleSelectionChange(selection)
        }
      }
    }
  },
  mounted() {
    console.log(this.dataForForm)
    this.formField.dlrFullName = this.dataForForm.dlrShortName
    this.formField.ttCode = this.dataForForm.ttCode
    this.formField.baseNum = this.dataForForm.baseNum
    this.formField.makingMonth = this.dataForForm.makingMonth
    this.formField.floatingCeiling = this.dataForForm.floatingCeiling
    this.formField.floatingFloor = this.dataForForm.floatingFloor
    setTimeout(() => {
      this.planMonth(this.dataForForm.makingMonth)
    }, 0)
  },
  methods: {
    reset() {
      this.formField.baseNum = ''
      this.formField.floatingCeiling = ''
      this.formField.floatingFloor = ''
    },
    // form表单组件每个元素所占栅格栏数每行24格
    spanNum() {
      return 24
    },
    planMonth(month) {
      month = month.substring(month.length - 2)
      let plan1 = `${month[0]}` + `${Number(month[1]) + 1}`
      let plan2 = `${month[0]}` + `${Number(month[1]) + 2}`
      let plan3 = `${month[0]}` + `${Number(month[1]) + 3}`
      if (Number(month) >= 1) {
        if (Number(month) === 7) {
          plan3 = `${Number(month[1]) + 3}`
        }
        if (Number(month) === 8) {
          plan2 = `${Number(month[1]) + 2}`
          plan3 = `${Number(month[1]) + 3}`
        }
        if (Number(month) === 9) {
          plan1 = `${Number(month[1]) + 1}`
          plan2 = `${Number(month[1]) + 2}`
          plan3 = `${Number(month[1]) + 3}`
        }
        this.formField.planM = `${plan1},${plan2},${plan3}`
      }
      if (Number(month) === 10) {
        plan3 = '01'
      }
      if (Number(month) === 11) {
        plan2 = '01'
        plan3 = '02'
      }
      if (Number(month) === 12) {
        plan1 = '01'
        plan2 = '02'
        plan3 = '03'
      }
      this.$refs.multipleTable.planM = `${plan1},${plan2},${plan3}`
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', type)
    },
    // 保存
    save() {
      const that = this
      // 先读取参数中的传输对象
      this.formField.proportionSetId = this.dataForForm.proportionSetId,
      this.formField.updateControlId = this.dataForForm.updateControlId
      const returnObj = {
      // api配置
        apiConfig: api.updateStorePlanScaleSet,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: this.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        that.$refs['multipleTable'].listLoading = false
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', duration: 2000 })
            that.closeEdit(1)
          }
          return
        } else {
          that.$refs['multipleTable'].listLoading = false
          this.$message({ message: response.msg, type: 'success', duration: 2000 })
          that.closeEdit(2)
        }
      }).catch(err => {
        console.info(err)
      })
    }
  }
}
</script>

